"use strict";
/**
 * 工具函数库
 */
const fs = require("fs");
function isObject(o) {
  return Object.prototype.toString.call(o) === "[object Object]";
}

function spinnerStart(msg, spinnerString = "|/-\\") {
  const Spinner = require("cli-spinner").Spinner;
  const spinnerLoad = new Spinner(msg + "%s");
  spinnerLoad.setSpinnerString(spinnerString);
  spinnerLoad.start();
  return spinnerLoad;
}
function sleep(timeout = 1000) {
  return new Promise((resolve) => setTimeout(resolve, timeout));
}

// node spawn命令在Windows及Mac系统下的兼容
function exec(command, args, options) {
  const win32 = process.platform === "win32";
  const cmd = win32 ? "cmd" : command;
  const cmdArgs = win32 ? ["/c"].concat(command, args) : args;
  return require("child_process").spawn(cmd, cmdArgs, options || {});
}

// 异步的exec封装
function execAsync(command, args, options) {
  return new Promise((resolve, reject) => {
    const p = exec(command, args, options);
    p.on("error", (e) => {
      reject(e);
    });
    p.on("exit", (c) => {
      resolve(c);
    });
  });
}

// 读取文件
function readFile(filePath, options = {}) {
  if (fs.existsSync(filePath)) {
    const buffer = fs.readFileSync(filePath);
    if (buffer) {
      if (options.toJson) {
        return buffer.toJSON();
      } else {
        return buffer.toString();
      }
    }
  }
  return null;
}

// 写入文件
function writeFile(filePath, data, { rewrite = true } = {}) {
  if (fs.existsSync(filePath)) {
    if (rewrite) {
      fs.writeFileSync(filePath, data);
      return true;
    }
    return false;
  } else {
    fs.writeFileSync(filePath, data);
    return true;
  }
}

module.exports = {
  isObject,
  spinnerStart,
  sleep,
  exec,
  execAsync,
  readFile,
  writeFile,
};
